package org.spotem.service;

import org.spotem.common.BaseException;
import org.spotem.dao.TrackPointRepo;
import org.spotem.dao.TrackRepo;
import org.spotem.model.TrackImpl;
import org.spotem.model.TrackPointImpl;
import org.spotem.model.UserImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.security.RolesAllowed;
import java.util.Date;
import java.util.List;

@Component
public class TrackService extends BaseService {

    @Autowired
    private TrackRepo trackRepo;
    @Autowired
    private TrackPointRepo trackPointRepo;
    @Autowired
    private UserService userService;

    @Transactional(readOnly = true, rollbackFor = BaseException.class)
//    @RolesAllowed(AuthService.PUBLIC_ACTION)
    public TrackImpl findTrack(String trackKey) {
        return trackRepo.findOne(trackKey);
    }

    @Transactional(readOnly = true, rollbackFor = BaseException.class)
//    @RolesAllowed(AuthService.PUBLIC_ACTION)
    public List<TrackPointImpl> findTrackPoints(String trackKey, Long minPointId) {
        return trackPointRepo.findPoints(trackKey, minPointId);
    }

    @Transactional(readOnly = false, rollbackFor = BaseException.class)
//    @RolesAllowed(AuthService.PUBLIC_ACTION)
    public boolean addTrackPoint(String trackKey, double lat, double lng) {
        TrackImpl track = findTrack(trackKey);
        if(track == null) {
            track = new TrackImpl();
            track.setKey(trackKey);
            track.setCreationDate(new Date());
            UserImpl anonymous = userService.findUser("anonymous");
            track.setOwner(anonymous);
            track = trackRepo.save(track);
        }
        TrackPointImpl trackPoint = new TrackPointImpl();
        trackPoint.setLatitude(lat);
        trackPoint.setLongitude(lng);
        trackPoint.setTime(new Date());
        trackPoint.setTrack(track);
        trackPointRepo.save(trackPoint);
        logger.info("added track point " + trackPoint + " to track " + trackKey);
        return true;
    }
}
